package cn.toolck.minitomcat.service;

import cn.toolck.minitomcat.runner.WorkExecutor;
import cn.toolck.minitomcat.runner.Worker;

import java.net.ServerSocket;
import java.net.Socket;

/**
 * @ClassName Connector
 * @Description TODO
 * @Author Toolck Rin
 * @Date 2021/3/18 0:54
 * @Version 1.0
 **/
public class Connector implements Runnable {
    private int port;
    private WorkExecutor executor = new WorkExecutor();
    private Service service;

    public Connector(int port) {
        this.port = port;
    }

    public Connector() {
    }

    @Override
    public void run() {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(port);
        } catch (Exception e) {
            e.printStackTrace();
        }
        while (true) {
            try {
                Socket socket = serverSocket.accept();
                // 启用工作线程进行请求处理
                Worker worker = new Worker(socket, service);
                executor.execute(worker);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public Service getService() {
        return service;
    }

    public void setService(Service service) {
        this.service = service;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public WorkExecutor getExecutor() {
        return executor;
    }

    public void setExecutor(WorkExecutor executor) {
        this.executor = executor;
    }
}
